<template>
  <div class="app-container">
    <div class="table">
      <el-form class="search-container" :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="分组名称" prop="groupName">
          <el-input v-model="queryParams.groupName" placeholder="请输入分组名称" clearable style="width: 200px" @keyup.enter="handleQuery" />
        </el-form-item>

        <el-form-item label="学院" prop="deptId">
          <el-select v-model="queryParams.deptId" placeholder="请选择学院" clearable style="width: 200px">
            <el-option v-for="item in deptOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker clearable v-model="queryParams.startTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择开始时间"></el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker clearable v-model="queryParams.endTime" type="date" value-format="YYYY-MM-DD" placeholder="请选择结束时间"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="table-container">
        <el-row :gutter="10" class="mb8">
          <span>毕业设计分组信息列表</span>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getList"
            add="system:group:add"
            @handleAdd="handleAdd"
            update="system:group:edit"
            @handleUpdate="handleUpdate"
            del="system:group:remove"
            @handleDelete="handleDelete"
            exp="system:group:export"
            @handleExport="handleExport"
            :single="single"
            :multiple="multiple"
          ></right-toolbar>
        </el-row>
        <el-table v-loading="loading" class="table-content" border :data="groupList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="分组名称" width="250" align="center" prop="groupName" />
          <el-table-column label="学院" align="center" prop="dept.deptName" />
          <el-table-column label="年级" align="center" prop="grade.gradeName" />
          <el-table-column label="分组专业" align="center">
            <template #default="{ row }">
              <span style="cursor: pointer; color: var(--el-color-primary)" @click="handleViewMajor(row)">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="分组教师" align="center">
            <template #default="{ row }">
              <span style="cursor: pointer; color: var(--el-color-primary)" @click="handleViewTeacher(row)">查看</span>
            </template>
          </el-table-column>
          <el-table-column label="队伍最大人数" align="center" prop="teamMax" />
          <el-table-column label="教师指导队伍数" align="center" prop="teacherMax" />
          <el-table-column label="开始时间" align="center" prop="startTime" width="180">
            <template v-slot="{ row }">
              <span>{{ parseTime(row.startTime, '{y}-{m}-{d}-{h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="endTime" width="180">
            <template v-slot="{ row }">
              <span>{{ parseTime(row.endTime, '{y}-{m}-{d}-{h}:{i}:{s}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
            <template v-slot="{ row }">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:group:edit']">修改</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:group:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination class="pagination-container" v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
      </div>
    </div>

    <index-dialog ref="dialogRef" @update="updateHandler"></index-dialog>
    <major-view-dialog ref="majorDialogRef"></major-view-dialog>
    <teacher-view-dialog ref="teacherDialogRef"></teacher-view-dialog>
  </div>
</template>

<script setup name="Group">
import { listGroup, getGroup, delGroup, addGroup, updateGroup } from '@/api/group'
import { getGradeTree } from '@/api/grade'
import { getCurrentInstance, ref, computed } from 'vue'
import indexDialog from './components/indexDialog.vue'
import MajorViewDialog from './components/MajorViewDialog.vue'
import TeacherViewDialog from './components/TeacherViewDialog.vue'
import { listTeacher } from '@/api/teacher'
import { listMajor } from '@/api/major'
const { proxy } = getCurrentInstance()

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const groupList = ref([])
const dialogRef = ref(null)
const majorDialogRef = ref(null)
const teacherDialogRef = ref(null)
const queryRef = ref(null)
const queryHandler = () => {
  queryParams.value.pageNum = 1
  getList()
}

const getList = () => {
  loading.value = true
  listGroup(queryParams.value).then((res) => {
    console.log('分组信息表列表', res.data)
    groupList.value = res.data.rows
    total.value = res.data.total
    loading.value = false
    // 确保名称映射已加载
    loadNameMaps()
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}
const gradeTree = ref([])
// 学院选项
const deptOptions = computed(() => {
  return gradeTree.value.map((item) => ({
    label: item.deptName,
    value: item.deptId
  }))
})
// 加载完整的树形数据
async function loadGradeTree() {
  const res = await getGradeTree()
  gradeTree.value = res.data || []
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.groupId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm('queryRef')
  queryHandler()
}
/** 修改按钮操作 */
const handleUpdate = (row) => {
  const groupId = row?.groupId || ids.value
  dialogRef.value.openDialog(groupId)
}
/** 新增按钮操作 */
const handleAdd = () => {
  dialogRef.value.openDialog()
}
/** 删除按钮操作 */
const handleDelete = (row) => {
  const groupId = row?.groupId || ids.value
  proxy.$modal
    .confirm('是否确认删除编号为"' + groupId + '"的数据项?')
    .then(function () {
      return delGroup(groupId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}
const updateHandler = () => {
  queryHandler()
}
const handleExport = () => {
  proxy.download('system/group/export', { ...queryParams.value }, `group_${new Date().getTime()}.xlsx`)
}
// 加载年级树形数据
loadGradeTree()
getList()

// 加载教师与专业名称映射，便于ID回显为文字
function loadNameMaps() {
  // 教师
  listTeacher({ pageNum: 1, pageSize: 1000 }).then((res) => {
    const rows = res?.data?.rows || []
    const map = {}
    rows.forEach((t) => {
      map[t.teacherId] = t.nickName
    })
    teacherMap.value = map
  })
  // 专业
  listMajor({ pageNum: 1, pageSize: 1000 }).then((res) => {
    const rows = res?.data?.rows || res?.rows || []
    const map = {}
    rows.forEach((m) => {
      map[m.majorId] = m.majorName
    })
    majorMap.value = map
  })
}

// 查看分组专业
const handleViewMajor = (row) => {
  majorDialogRef.value.openDialog(row.majors || [])
}

// 查看分组教师
const handleViewTeacher = (row) => {
  teacherDialogRef.value.openDialog(row.teachers || [])
}
</script>
